package pers.li.controller.user;

import pers.li.service.UserService;
import pers.li.utils.PublicUtils;
import pers.li.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/user/updatePassword.action")
public class UpdatePassword extends HttpServlet {
    private final UserService userService = new UserService();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer userId = PublicUtils.getLoginUserId(req);
        String oldPassword = req.getParameter("oldPassword");
        String newPassword = req.getParameter("newPassword");
        User user = userService.getUserById(userId);
        if (user != null && user.getUserPass().equals(oldPassword)){
            userService.updatePassword(newPassword,userId);
            req.getSession().removeAttribute("login");
            resp.sendRedirect(req.getContextPath() + "/user/update_password.jsp");
        }
    }
}
